package com.aoxon.cargo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.util.Log;


public class FileUtil {

	private static final String TAG = "FileHelper";
	
	
	/**
	 * 判断文件保存路径是否可用
	 * @param filePath
	 * @return
	 */
	public static boolean fileIsExist(String filePath){
		if(filePath == null || filePath.length() < 1){
			Log.e(TAG,"param invalid, filePath: " + filePath);
			return false;
		}
		
		File f = new File(filePath);
		if(!f.exists()){
			return false;
		}
		return true;
	}
	
	/**
	 * 保存文件并返回文件输入流
	 * @param filePath
	 * @return
	 */
	public static InputStream readFile(String filePath){
		if(null == filePath){
			Log.e(TAG, "param invalid, filePath: " + filePath);
			return null;
		}
		InputStream is = null;
		
		try{
			if(fileIsExist(filePath)){
				File f = new File(filePath);
				is = new FileInputStream(f);
			}else{
				return null;
			}
		}catch (Exception e){
			Log.e(TAG, "Exception, e:" + e.toString());
			return null;
		}
		return is;
	}
	
	
	/**
	 * 创建文件保存路径
	 * @param filePath
	 * @return
	 */
	public static boolean createDirectory(String filePath){
		if(null == filePath){
			return false;
		}
		
		File file = new File(filePath);
		
		if(file.exists()){
			return true;
		}
		
		return file.mkdirs();
	}
	
	
	/**
	 * 删除指定目录下的所有文件
	 * (包括子文件夹里的文件)
	 * @param filePath
	 * @return
	 */
	public static boolean deleteDirectory(String filePath){
		if(null == filePath){
			Log.e(TAG,"Invalid param. filePath: " + filePath);
			return false;
		}
		File file = new File(filePath);
		
		if(file == null || file.exists()){
			return false;
		}
		
		if(file.isDirectory()){
			File[] fileList = file.listFiles();
			for(int i=0; i < fileList.length; i++){
				if(fileList[i].isDirectory()){
					deleteDirectory(fileList[i].getAbsolutePath());
				}else{
					fileList[i].delete();
					Log.d(TAG, "delete filePath: " + fileList[i].getAbsolutePath());
				}
			}
		}
		
		Log.d(TAG, "delete filePath: " + file.getAbsolutePath());
		file.delete();
		return true;
	}
	
}
